var authop = require('authop.js');


function get_m(){
  var app = getApp(); 
  if(!app.globalData["xcsys"] ||!app.globalData["xcsys"]['m'])
  {
    var nowPage = getCurrentPages();
    app.globalData["xcsys"]={};
    if (nowPage.length) {
      nowPage = nowPage[getCurrentPages().length - 1];        
      app.globalData["xcsys"]["m"]=nowPage.__route__.split('/')[0];
    }
  }
  return app.globalData["xcsys"]["m"]
}
// 加载系统配制 不需要微擎登录
function loadconfig(that, Refresh) {
  var app = getApp(); 
//  取模块名
    if(! app.globalData["xcsys"]){
      var nowPage = getCurrentPages();
      app.globalData["xcsys"]={};
      if (nowPage.length) {
        nowPage = nowPage[getCurrentPages().length - 1];        
        app.globalData["xcsys"]["m"]=nowPage.__route__.split('/')[0];
      }

      var app = getApp()

      app.globalData["xcsys"]["basicurl"]=app.siteInfo.siteroot.replace('/app/index.php','')
      
    }
    var shareid=""       
  if (that.data.options && that.data.options.scene) {
    that.data.options["shareid"] = that.data.options.scene.split("_")[0];    
    /**谁分享的 */
    app.globalData.share.shareid= that.data.options["shareid"];
  }
 
 



  if (!app.globalData.configdata || Refresh) {

    if(that.data.options["shareid"] ){
      shareid=that.data.options["shareid"] 

      
    }   
    return  getserverconfing(shareid)
  
  }
  else
  {


    return new Promise(resolve=>{
      resolve({xcsys:app.globalData["xcsys"],configdata:app.globalData.configdata,userfunc:getuserinfo(false,shareid)}) 
     
    })
  }

  
}
//获取用户信息
function getuserinfo(refresh,shareid,){
  var app = getApp();
  if( !refresh && app.globalData.member){
    return  new Promise(function(resolve){
      resolve({status:"1",message:"",obj:app.globalData.member});
    })
  }

   var userInfo= wx.getStorageSync('userInfo');   
   return new Promise(function (resolve, reject) { 
    wx.login({
      success: function (res) { 
        var data={code: res.code}
        if(shareid){
          data["shareid"]=shareid;
        }
        app.util.requestnologin({
          'url': 'entry/wxapp/sys_session',
          // data: { code: res.code },
          data,
          cachetime: 0,
          showLoading: false,
          success: function (session) {             
            if (!session.data.errno) {
              var userInfo={}
              userInfo.sessionid = session.data.data.sessionid                
             var member= session.data.data.member
              if(member){
                app.globalData.member=member
                if(member.member_id!="0")
                {                   
                  app.globalData.isreg=true;
                }
              }
              app.globalData.islogin=true;  

              wx.setStorageSync('userInfo', userInfo);
              resolve({status:"1",message:"",obj:session.data.data.member});
            }
            else
            {
               resolve({status:"-1",message:session.data.message})
            }
          }
        })
      }
    })
   }) 
  
}
//获取服务器配制
function  getserverconfing(shareid){
  var app =getApp();
  return new Promise(function (resolve, reject) {
    var data = {};
    data["op"] = "init";
    app.util.requestnologin({
      'url': 'entry/wxapp/sys_config',
      showLoading: false,
      'data': data,
      success: function (res) {       
        if (res.data.errno == 0) {         
          var xcresult = res.data.data;
          if (xcresult["status"] == 1) {
            app.globalData.configdata = xcresult["obj"];
            if(!app.globalData.configdata["basic"]["homeurl"]){
              app.globalData.configdata["basic"]["homeurl"]="/xc_lshop/index/index"
            }
             
            if(  app.globalData.configdata["basic"]&&  app.globalData.configdata["basic"]["status"]==1){
 

              //闭站处理
              wx.redirectTo({
                url: "/"+app.globalData["xcsys"]["m"]+"/syspage/closed",
              })
            } 
            resolve({xcsys:app.globalData["xcsys"],configdata:app.globalData.configdata,userfunc:getuserinfo(false,shareid)});   
            
          }
          else {
            reject(xcresult);
          }
        }       
      },
      fail: function (res) {
        reject({staus:-1001,"obj":res,"message":"请求失败"});
      },
      
    })
  })
}
  
//加载配制数据
function setpagelayout($that, $_app) {
  var footnav = $that.selectComponent("#footer");
  if (footnav && $_app.globalData.configdata["bottomnav"]) {
    footnav.setnavdata();
  }   
}
var xcrouter = {}

xcrouter.diynavigateTo=function(cid,url, appid){



  if( typeof(cid)=="object" ){
    url=cid.url  //链接，直播内容
    appid=cid.appid //appid ,房间号
    cid= cid.cid
   
  }

  
  if(cid==1){
    xcrouter.navigateTo(url)
  }else if(cid==2){
    //makePhoneCall
  }
  
  else if(cid ==4){

    wx.navigateToMiniProgram({    
      appId: appid,
      path:url
    })
   //外连接
  }else if(cid ==5){
    var app=getApp()

    
    url:app.globalData.temurl=url
    xcrouter.navigateTo("/xc_lshop/syspage/h5")
    
  //H5链接
  }else if(cid ==8){
    // var app=getApp()

    
    // url:app.globalData.temurl=url
    // xcrouter.navigateTo("/xc_lshop/syspage/h5")
    
    // var dataset = e.currentTarget.dataset;
    // var roomId = dataset.roomid // 填写具体的房间号，可通过下面【获取直播房间列表】 API 获取
    // var customParams = encodeURIComponent(JSON.stringify({
      // roomid: roomId

    // })) // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
    url=encodeURIComponent(JSON.stringify({roomid: appid}))
    xcrouter.navigateTo( `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${appid}&custom_params=${url}`)
  }



}
 


xcrouter.navigateTo = function (params) {

  if(!params)
  {
    console.log("未设定跳转链接")
    return ;
  }
 
  if(typeof(params)=="string"){
    params={url:params}
  }
  var $_pages = getCurrentPages();
  var plen = $_pages.length;
  if (plen < 9) {
    wx.navigateTo(params)
  }
  else {


    wx.redirectTo(params)
  }
} 
function getshareurl(mode){
  var app= getApp();
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options
  var paradata=[]
  for(var a in options){
    paradata.push(a+"="+options[a]);
  }
  if(mode=='para'){
    return paradata.join("&");
  }


  if(app.globalData.member && app.globalData.member.member_id){
    paradata.push("shareid="+app.globalData.member.member_id)
  }
  var url = `/${currentPage.route}`
  if(paradata.length>0){
    url+="?"+paradata.join("&")
  }
  return url
}
  //加载其它导航栏
function loadfootnav(keyval){

 var data={}
 data["keyval"]=keyval
 data["op"]="footnav"


 return new Promise(function (resolve, reject) {
var app =getApp()
  app.util.request({
    'url': 'entry/wxapp/sys_config',
    showLoading: false,
    'data': data, 
    success: function (res) {       
      if (!res.data.errno) {

        var rdata= res.data.data
        if(rdata["status"]==1){
          app.globalData.footnav[keyval]=rdata["obj"]
        }
        resolve(rdata);
        
      
      }
      else
      {
         resolve({status:"-1",message:session.data.message})
      }
    }
  })
})
}
 
//
// export default { get: iget, post: ipost }
module.exports = {
  getshareurl:getshareurl,
  getuserinfo:getuserinfo,
  authop :authop ,
  router:xcrouter,
  loadconfig: loadconfig,
  loadfootnav:loadfootnav, //特殊导航栏
  setpagelayout:setpagelayout,
  get_m:get_m
}